from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.core.files.storage import default_storage
import uuid
import os
from django.conf import settings
# 文件上传接口
@csrf_exempt
def upload_file(request):
    if request.method == 'POST':
        file = request.FILES.get('file')
        print(file,'==上传的文件对象==')
        if file:
            # 生成一个uuid作为文件名
            ext = file.name.rsplit('.')[-1]
            fileName = str(uuid.uuid4()) + "." + ext
            file_path = settings.MEDIA_ROOT + 'images\\' + fileName
            print('============',file_path)
            # 保存文件
            with default_storage.open(file_path, 'wb+') as destination:
                for chunk in file.chunks():
                    destination.write(chunk)
            # 返回文件的URL或路径
            file_url = '/media/images/' + fileName
            print(file_url,'==上传的文件路径==')
            response_data = {
                "errno": 0, #注意：值是数字，不能是字符串
                "data": {
                    "url": file_url # 图片 src ，必须
                }
            }
            return JsonResponse(response_data,json_dumps_params={'ensure_ascii': False})
        else:
            response_data = {
                'errno': 1,
                'message': '没有文件上传',
            }
            return JsonResponse(response_data, status=400,json_dumps_params={'ensure_ascii': False})
    else:
        response_data = {
            'errno': 1,
            'message': '请求方式错误',
        }

    return JsonResponse(response_data, status=405,json_dumps_params={'ensure_ascii': False})

# 文件物理删除接口
@csrf_exempt
def delete_file(request): 
    file= request.POST.get('file')
    filename =file.split('/')[-1]
    file_path = os.path.join('uploads/', filename)
    print(file_path,'==删除的文件路径==')
    default_storage.delete(file_path)
    return JsonResponse({'message': '文件物理删除接口'})